/**
 * 富文本
 * https://www.wangeditor.com/v5/for-frame.html#%E5%AE%89%E8%A3%85-2
 */

import React, { useState, useEffect } from "react";
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-react";

import { uploadImage } from "@/api/goods";

function MyEditor({ value, onChange }) {
  const [editor, setEditor] = useState(null); // 存储 editor 实例
  const [html, setHtml] = useState(value);

  useEffect(() => {
    setHtml(value);
  }, [value]);

  const toolbarConfig = {
    // 所有的key
    // ["bold","underline","italic","through","code","sub","sup","clearStyle","color","bgColor","fontSize","fontFamily","indent","delIndent","justifyLeft","justifyRight","justifyCenter","justifyJustify","lineHeight","insertImage","deleteImage","editImage","viewImageLink","imageWidth30","imageWidth50","imageWidth100","divider","emotion","insertLink","editLink","unLink","viewLink","codeBlock","blockquote","headerSelect","header1","header2","header3","header4","header5","todo","redo","undo","fullScreen","bulletedList","numberedList","insertTable","deleteTable","insertTableRow","deleteTableRow","insertTableCol","deleteTableCol","tableHeader","tableFullWidth","insertVideo","uploadVideo","uploadImage","codeSelectLang"]
    // 这里我们去掉 视频相关的
    excludeKeys: ["insertVideo", "uploadVideo"],
  };

  const editorConfig = {
    placeholder: "请输入内容...",
    MENU_CONF: {
      uploadImage: {
        // server: "/common/uploadImage",
        // fieldName: "file",
        // // 单个文件的最大体积限制，默认为 2M
        // maxFileSize: 10 * 1024 * 1024, // 10M

        // // 最多可上传几个文件，默认为 100
        // maxNumberOfFiles: 1,

        // // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
        // allowedFileTypes: ["image/*"],

        // 自定义上传
        async customUpload(file, insertFn) {
          console.log("file===", file);
          // file 即选中的文件
          // 自己实现上传，并得到图片 url alt href
          const isJPG =
            file.type === "image/jpeg" ||
            file.type === "image/png" ||
            file.type === "image/jpg";
          if (!isJPG) {
            message.info("请上传png,jpg格式图片!");
          } else {
            const formData = new FormData();
            formData.append("file", file);
            const res = await uploadImage(formData);
            const url = res.data;

            // 最后插入图片
            insertFn(url, file.name, "");
          }
        },
      },
    },
  };

  // 及时销毁 editor
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  return (
    <>
      <div style={{ border: "1px solid #ccc", zIndex: 100 }}>
        <Toolbar
          editor={editor}
          defaultConfig={toolbarConfig}
          mode="simple"
          style={{ borderBottom: "1px solid #ccc" }}
        />
        <Editor
          defaultConfig={editorConfig}
          value={html}
          onCreated={setEditor}
          onChange={(editor) => {
            const value = editor.getHtml();
            const text = editor.getText();
            if (text.trim()) {
              setHtml(value);
              onChange(value);
            } else {
              setHtml("");
              onChange("");
            }
          }}
          mode="default"
          style={{ height: "500px" }}
        />
      </div>
    </>
  );
}

export default MyEditor;
